package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xmy.cultivate.constants.MqConstants;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.IMqSchedulingLogService;
import com.xmy.cultivate.service.IWecharPushService;
import com.xmy.cultivate.service.IWecharsBindService;
import com.xmy.cultivate.util.CommonUtil;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Service
public class WecharPushServiceImpl implements IWecharPushService {


    @Autowired
    CourseSchedulingDetailMapper courseSchedulingDetailMapper;

    @Autowired
    StudentGradeMapper studentGradeMapper;

    @Autowired
    IWecharsBindService iWecharsBindService;

    @Autowired
    StudentMapper studentMapper;

    @Autowired
    OrderDetailMapper orderDetailMapper;

    @Autowired
    IMqSchedulingLogService iMqSchedulingLogService;


    @Autowired
    RabbitTemplate rabbitTemplate;
    @Autowired
    private RecordCourseMapper recordCourseMapper;

    @Override
    public void delayClassRemind(MultiDelayMessage<MqSchedulingLog> multiDelayMessage) {
//        MqSchedulingLog mqSchedulingLog = multiDelayMessage.getData();
//        List<RepairCourse> repairCourseList = courseSchedulingDetailMapper.getSchedulingUnionRepairForId(mqSchedulingLog.getId());
//        LocalDateTime dateTimeNow = LocalDateTime.now().withNano(0);
//        for (RepairCourse repairCourse : repairCourseList) {
//            //状态为0表示还未记上课的，开始上课时间相等
//            if (repairCourse.getStatus().equals(0) && repairCourse.getStartDateTime().equals(mqSchedulingLog.getStartDateTime())) {
//
//                if (dateTimeNow.isBefore(repairCourse.getStartDateTime())){
//                    this.attendClassRemind(repairCourse);
//                }
//
//                if (multiDelayMessage.hasNextDelay()) {
//                    int delayVal = multiDelayMessage.removeNextDelay().intValue();
//                    rabbitTemplate.convertAndSend(MqConstants.EXCHANGE_DELAY_CLASS_REMIND_DIRECT, null, multiDelayMessage, new MessagePostProcessor() {
//                        @Override
//                        public Message postProcessMessage(Message message) throws AmqpException {
//                            // 添加延迟消息属性
//                            Integer delayNum = 1000 * delayVal;
//                            message.getMessageProperties().setDelay(delayNum);
//                            return message;
//                        }
//                    });
//                    MqSchedulingLog mqSchedulingLogInfo = iMqSchedulingLogService.getById(mqSchedulingLog.getId());
//                    if (mqSchedulingLogInfo != null) {
//                        mqSchedulingLogInfo.setStatus(1);
//                        Integer delaySecond = delayVal;
//                        mqSchedulingLogInfo.setExecuteTime(mqSchedulingLogInfo.getExecuteTime().plusSeconds(delaySecond));
//                        mqSchedulingLogInfo.setDelayedSecond(Long.parseLong(delaySecond.toString()));
//                        mqSchedulingLogInfo.setRemark("执行时间："+LocalDateTime.now().withNano(0)+"，下一次执行差：" + delaySecond+"秒");
//                        iMqSchedulingLogService.updateById(mqSchedulingLogInfo);
//                    }
//                } else {
//                    UpdateWrapper<MqSchedulingLog> mqSchedulingLogUpdateWrapper = new UpdateWrapper<>();
//                    mqSchedulingLogUpdateWrapper.eq("id", mqSchedulingLog.getId());
//                    mqSchedulingLogUpdateWrapper.set("status", 2);
//                    mqSchedulingLogUpdateWrapper.set("remark","执行时间："+LocalDateTime.now().withNano(0)+"，执行完成");
//                    iMqSchedulingLogService.update(mqSchedulingLogUpdateWrapper);
//                }
//            }
//        }
    }

    @Override
    public void attendClassRemind(RepairCourse repairCourse) {
        try {
            if (!repairCourse.getLessonType().equals(1)) {
                //智能课、刷题班
                this.otherCourse(repairCourse);
            } else {
                //精品课
                this.boutiqueCourse(repairCourse);
            }
        }catch (Exception e){

        }

    }

    /**
     * 精品课推送
     *
     * @param repairCourse
     */
    private void boutiqueCourse(RepairCourse repairCourse) {
        //1按班级正常排课、调课，2按学员调课、补课，消课
        if (repairCourse.getSchedulingType().equals(1)) {
            //课程类别：1精品课，2智能课，3补课，4调课，5消课
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("grade_id", repairCourse.getGradeId());
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.notInSql("student_id", "select student_id from repair_course where deleted=0 and out_scheduling_detail_id=" + repairCourse.getId() + "");
            studentGradeQueryWrapper.groupBy("student_id");
            List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
            //System.out.println("studentGradeListCount:"+studentGradeList.size());
            for (StudentGrade studentGrade : studentGradeList) {
                try {
                    Integer yearAndQuarter = Integer.parseInt(studentGrade.getYearPart() + "" + studentGrade.getQuarterNum());
                    Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(studentGrade.getSchoolId(), studentGrade.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, studentGrade.getLessonType());
                    Integer leaveCount = recordCourseMapper.getLeaveCount(studentGrade.getYearPart(),studentGrade.getQuarterNum(),studentGrade.getLessonType(),studentGrade.getStudentId(),studentGrade.getSubjectsId());
                    if (residueCourseCount > 0 || leaveCount>0) {
                        Student student = studentMapper.selectById(studentGrade.getStudentId());
                        if (student != null) {
                            if (repairCourse.getCourseType().equals(1)) {
                                //班级里的上课学生
                                StringBuilder first = new StringBuilder();
                                first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”上课提醒");

                                //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                                String keyword1 = this.replaceGradeName(repairCourse.getGradeName(), repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());

                                StringBuilder keyword2 = new StringBuilder();
                                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                                // 使用formatter格式化LocalDateTime
                                String sortDateTime = repairCourse.getStartDateTime().format(formatter);
                                //String sortDateTime = repairCourse.getStartDateTime().toString();

                                //keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                                keyword2.append(sortDateTime);


                                StringBuilder remark = new StringBuilder();
                                remark.append("如有疑问，请与老师联系");
                                List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                                //iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId()+);
                                Long msgIdL = System.currentTimeMillis() / 1000;
                                String msgId = msgIdL.toString();
                                iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), msgId);
                            } else {
                                //班级里的调课学生
                                StringBuilder first = new StringBuilder();
                                first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”上课提醒");
                                String keyword1 = "";
                                if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                                    keyword1 = this.replaceGradeName(repairCourse.getGradeName(), repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                                } else {
                                    //String teacherName =  studentGradeMapper.getTeacherNameForGradeId(studentGrade.getGradeId());
                                    keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();

                                }

                                StringBuilder keyword2 = new StringBuilder();
                                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                                // 使用formatter格式化LocalDateTime
                                String sortDateTime = repairCourse.getStartDateTime().format(formatter);
                                //String sortDateTime = repairCourse.getStartDateTime().toString();
                                if (repairCourse.getCourseType().equals(3) || repairCourse.getCourseType().equals(6)){
                                    sortDateTime = repairCourse.getSchoolDate()+" "+ repairCourse.getTimeStart()+"-"+repairCourse.getTimeEnd();
                                }
                                keyword2.append(sortDateTime);
                                //keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                                StringBuilder remark = new StringBuilder();
                                remark.append("如有疑问，请与老师联系");
                                List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                                //iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                                Long msgIdL = System.currentTimeMillis() / 1000;
                                String msgId = msgIdL.toString();
                                iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), msgId);
                            }
                        }
                    }
                }catch (Exception e){

                }
            }
        } else if (repairCourse.getSchedulingType().equals(2)) {
            Integer yearAndQuarter = Integer.parseInt(repairCourse.getYearPart() + "" + repairCourse.getQuarter());
            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(repairCourse.getSchoolId(), repairCourse.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, repairCourse.getLessonType());
            Integer leaveCount = recordCourseMapper.getLeaveCount(repairCourse.getYearPart(),repairCourse.getQuarter(),repairCourse.getLessonType(),repairCourse.getStudentId(),repairCourse.getSubjectsId());
            if (residueCourseCount > 0 || leaveCount>0) {
                Student student = studentMapper.selectById(repairCourse.getStudentId());
                if (student != null) {
                    StringBuilder first = new StringBuilder();
                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“精品课”上课提醒");

                    String keyword1 = "";
                    if (StringUtils.isNotBlank(repairCourse.getGradeName())) {
                        keyword1 = this.replaceGradeName(repairCourse.getGradeName(), repairCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                    } else {
                        keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName();
                        try {
                            RecordCourse recordCourse = studentGradeMapper.getLastReadingGrade(repairCourse.getYearPart(), repairCourse.getQuarter(), repairCourse.getSchoolId(), repairCourse.getSubjectsId(), repairCourse.getStudentId());
                            String gradeName = recordCourse.getGradeName();
                            gradeName = this.replaceGradeName(gradeName, recordCourse.getTeacherName(), student.getName(), repairCourse.getSubjectsName());
                            keyword1 = gradeName;
                        } catch (Exception e) {
                        }
                    }

                    StringBuilder keyword2 = new StringBuilder();
                    //keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");

                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
                    // 使用formatter格式化LocalDateTime
                    String sortDateTime = repairCourse.getStartDateTime().format(formatter);
                    keyword2.append(sortDateTime);

                    StringBuilder remark = new StringBuilder();
                    remark.append("如有疑问，请与老师联系");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(repairCourse.getStudentId());
                    iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                }
            }
        }
    }

    /**
     * 智能课，或者刷题班
     *
     * @param repairCourse
     */
    private void otherCourse(RepairCourse repairCourse) {

        Integer lessonType = 1;//这里计算精品课的剩余课时

        if (repairCourse.getSchedulingType().equals(1)) {
            //课程类别：1精品课，2智能课，3补课，4调课，5消课
            QueryWrapper<StudentGrade> studentGradeQueryWrapper = new QueryWrapper<>();
            studentGradeQueryWrapper.eq("grade_id", repairCourse.getGradeId());
            studentGradeQueryWrapper.eq("reading_status", 1);
            studentGradeQueryWrapper.eq("status", 1);
            studentGradeQueryWrapper.eq("deleted", 0);
            studentGradeQueryWrapper.notInSql("student_id", "select student_id from repair_course where deleted=0 and out_scheduling_detail_id=" + repairCourse.getId() + "");
            studentGradeQueryWrapper.groupBy("student_id");
            List<StudentGrade> studentGradeList = studentGradeMapper.selectList(studentGradeQueryWrapper);
            //System.out.println("studentGradeListCount:"+studentGradeList.size());

            String lessonName = CommonUtil.getLessonTypeName(repairCourse.getLessonType());

            for (StudentGrade studentGrade : studentGradeList) {
                Integer yearAndQuarter = Integer.parseInt(studentGrade.getYearPart() + "" + studentGrade.getQuarterNum());
                Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(studentGrade.getSchoolId(), studentGrade.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, lessonType);
                if (residueCourseCount > 0) {
                    Student student = studentMapper.selectById(studentGrade.getStudentId());
                    if (student != null) {
                        StringBuilder first = new StringBuilder();
                        first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“" + lessonName + "”上课提醒");

                        //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                        //【刘小铭】英语智能课/刷题班
                        String keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName() + lessonName;
                        StringBuilder keyword2 = new StringBuilder();
                        keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                        StringBuilder remark = new StringBuilder();
                        remark.append("如有疑问，请与老师联系");
                        List<String> opendIdList = iWecharsBindService.getSendOpenid(studentGrade.getStudentId());
                        iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                    }
                }
            }
        } else if (repairCourse.getSchedulingType().equals(2)) {
            Integer yearAndQuarter = Integer.parseInt(repairCourse.getYearPart() + "" + repairCourse.getQuarter());
            Integer residueCourseCount = orderDetailMapper.getResidueCourseCountForSubjects(repairCourse.getSchoolId(), repairCourse.getStudentId(), repairCourse.getSubjectsId(), yearAndQuarter, lessonType);
            if (residueCourseCount > 0) {
                Student student = studentMapper.selectById(repairCourse.getStudentId());
                String lessonName = CommonUtil.getLessonTypeName(repairCourse.getLessonType());
                if (student != null) {
                    StringBuilder first = new StringBuilder();
                    first.append(student.getName() + "有一条" + repairCourse.getSubjectsName() + "“" + lessonName + "”上课提醒");

                    //班级名，如果存在老师名称，用学生名把老师名替换，格式如：【刘小铭】英语六（3）班
                    //【刘小铭】英语智能课/刷题班
                    String keyword1 = "【" + student.getName() + "】" + repairCourse.getSubjectsName() + lessonName;
                    StringBuilder keyword2 = new StringBuilder();
                    keyword2.append(repairCourse.getStartDateTime().toString().replace("T", " ") + "上课");
                    StringBuilder remark = new StringBuilder();
                    remark.append("如有疑问，请与老师联系");
                    List<String> opendIdList = iWecharsBindService.getSendOpenid(repairCourse.getStudentId());
                    iWecharsBindService.wxPushOnCourse(opendIdList, first.toString(), keyword1, keyword2.toString(), remark.toString(), repairCourse.getId() + "" + repairCourse.getStudentId());
                }
            }
        }
    }


    private String replaceGradeName(String gradeName, String teacherName, String studentName, String subjectsName) {
        String keyword1 = gradeName;
        if (keyword1.contains("【" + teacherName + "】")) {
            keyword1 = keyword1.replace("【" + teacherName + "】", "【" + studentName + "】" + subjectsName);
        } else if (keyword1.contains("【" + subjectsName + "】")) {
            keyword1 = keyword1.replace("【" + subjectsName + "】", "【" + studentName + "】" + subjectsName);
        } else if (keyword1.contains(teacherName)) {
            keyword1 = keyword1.replace(teacherName, studentName);
            keyword1 += subjectsName;
        } else {
            keyword1 = "【" + teacherName + "】" + subjectsName + keyword1;
        }
        return keyword1;
    }
}
